import { ref, watch, onBeforeMount } from 'vue'
import router, { useRoute } from '/@/router'

const routerPath = ['/', '/error']

export default function () {
  const route = useRoute()

  let HeadActiveIndex = ref(0)

  // 高亮导航栏
  function brightIndex(path: string) {
    HeadActiveIndex.value = getBrightIndex(path)
  }

  onBeforeMount(() => {
    brightIndex(route.path)
  })

  watch(route, (newPath) => {
    brightIndex(newPath.path)
  })

  return { HeadActiveIndex }
}

// 跳转导航栏
export function routerJump(index: number) {
  router.push(getRouterPath(index) as string)
}

// 通过下标获得路由
function getRouterPath(active: number) {
  return routerPath[active]
}

// 通过路由获得下标
function getBrightIndex(path: string) {
  return getArrayIndex(routerPath, path)
}

// 通过值获得数组下标
function getArrayIndex(arr: Array<string>, obj: string) {
  var i = arr.length
  while (i--) {
    if (arr[i] === obj) {
      return i
    }
  }
  return -1
}


// 查找值下标代码优化
function getIndex(arr: Array<string>, obj: string) {
    return arr.findIndex(i => i == obj)
}
